
#define GL_GLEXT_PROTOTYPES

#include "openglframe.h"
#include <algorithm>

OpenGLFrame::OpenGLFrame(QWidget* parent, const QGLWidget* shareWidget, Qt::WFlags f)
   : QGLWidget(parent, shareWidget, f), 
      arcball(1,1) {
   
   // for keyboard use 
   //~ setFocusPolicy(Qt::StrongFocus);
   
   cursor3D = Point3(0,0,0);
   interactionMode = VIEW_MODE;
   
   texFloor = 0;
   
   fovy = 40.0;
   zoomFactor = 1.0;
   meshrendermode_mask = 0x20;
   
   isProjOrtho = true; // orthographic projection
   is_lightingOn = true;
   
   nmaxframes = 0;
   is_pic_capturing = true;
   is_mesh_capturing = false;
   id_picgrab = 0;
   
   njoints = nvertices = nfaces = 0;
   
   sceneT.identity();
   
   viewitems_mask = 0x0; 
   viewitems_mask = viewitems_mask | MODELDEF;
   viewitems_mask = viewitems_mask | SKELETONDEF;
   //~ viewitems_mask = viewitems_mask | KEYPOINTS;
   //~ viewitems_mask = viewitems_mask | CONSTRAINTS;
   viewitems_mask = viewitems_mask | FLOOR;
   viewitems_mask = viewitems_mask | INFO;
   viewitems_mask = viewitems_mask | SHADOW;
   
   // Floor and shadow specificacion
   floor[0] = Point3(-4.5,-0.01, 4.5);
   floor[1] = Point3( 4.5,-0.01, 4.5);
   floor[2] = Point3( 4.5,-0.01,-4.5);
   floor[3] = Point3(-4.5,-0.01,-4.5);
   pfloor = Plane3(floor[0], floor[2], floor[1]);
   
   float l[] = {3.0, 5.0, 5.0}; // Coordinates of the light source
   float e[] = {0.0, 0.0, 0.0};  // Point of the floor plane
   float n[] = {0.0, -1.0, 0.0}; // Normal vector for the plane
   createShadowProjectionMatrix(l,e,n);
   
   mincoo[0] = mincoo[1] = mincoo[2] = -1.0;
   mincoo[0] = mincoo[1] = mincoo[2] =  1.0;
   
   float c0[] = {1.0,0.0,0.0,1.0};
   float c1[] = {0.0,1.0,0.0,1.0};
}

OpenGLFrame::~OpenGLFrame() {
   
   for (unsigned i=0; i<models.size(); ++i) {
      if (models[i] != 0)      delete models[i];
      if (motions[i] != 0)     delete motions[i];
      if (animators[i] != 0)   delete animators[i];
      if (tmatrices[i] != 0)   delete tmatrices[i];
   }
}

/// Sets the interaction mode
void OpenGLFrame::setInteractionMode(InteractionMode m) {
   
   interactionMode = m;
}

bool OpenGLFrame::loadShape(const QString& filename) {
   
   QFileInfo fi(filename);
   QString extension = fi.suffix();
   MeshWithSkeleton *newmodel = 0;
   if (extension == "off") {
      newmodel = MeshWithSkeleton::load_off(filename.toStdString().c_str());
   }
   else if (extension == "ply") {
      newmodel = MeshWithSkeleton::load_ply(filename.toStdString().c_str());
   }
   else {
      return false;
   }
   
   if (newmodel) {
      
      nvertices += newmodel->nvertices(); 
      nfaces += newmodel->nfaces();
      models.push_back(newmodel);
      
      /// OpenGL vertex arrays setup
      //~ glEnableClientState(GL_VERTEX_ARRAY);
      //~ glEnableClientState(GL_NORMAL_ARRAY);
      //~ typedef Mesh::Vertex Vertex;
      //~ Vertex_iterator vi = currentmodel->vertices_begin();
      //~ glVertexPointer(3, GL_FLOAT, sizeof(Vertex), &(vi->point()[0]));
      //~ glNormalPointer(GL_FLOAT, sizeof(Vertex), &(vi->normal()[0]));
      
      genWorldLimits();
      setGLview();
      
      sceneT.identity();
      
      return true;
   }
   return false;
}

bool OpenGLFrame::loadSkeleton(const QString& filename) {
   
   if (models.empty()) return false;
   models.back()->loadSkeleton(filename.toStdString().c_str());
   njoints += models.back()->skeleton->nJoints();
   return true;
}

bool OpenGLFrame::loadSkinning(const QString& filename) {
   
   if (models.empty()) return false;
   if (filename.contains(".sj"))
      models.back()->loadSkinningOnJoints(filename.toStdString().c_str());
   else if (filename.contains(".sb"))
      models.back()->loadSkinningOnBones(filename.toStdString().c_str());
   return true;
}

bool OpenGLFrame::loadMotion(const QString& filename) {
   
   QFileInfo fi(filename);
   QString extension = fi.suffix();
   if (extension == "pss") {
      Motion *newmotion = Motion::load(filename.toStdString().c_str());
      (nmaxframes<newmotion->size())? (nmaxframes=newmotion->size()):0;
      motions.push_back(newmotion);
      return true;
   }
   return false;
}

void OpenGLFrame::loadTranslation(const Number t[3]) {
   
   typedef AMatrix<GLfloat> ATMatrix;
   ATMatrix *t0 = new ATMatrix;
   t0->identity();
   t0->translation(t[0], t[1], t[2]);
   tmatrices.push_back(&(*t0));
}

void OpenGLFrame::buildAnimators() {
   
   cout<<"buildAnimators() ... end"<<endl;
   assert(models.size() == motions.size() and motions.size() == tmatrices.size());
   for (unsigned i=0; i<models.size(); ++i) {
      animators.push_back(new Animator(models[i], motions[i]));
   }
   cout<<"buildAnimators() ... end"<<endl;
}

/// OpenGL initialization.
void OpenGLFrame::initializeGL() {
   
   glEnable(GL_LIGHTING);
   glEnable(GL_LIGHT0);
   glEnable(GL_LIGHT1);
   glEnable(GL_DEPTH_TEST);
   glEnable(GL_NORMALIZE);
   
   // lighting setup
   GLfloat left_light_position[] =  {0.0f, 2.0f, 2.0f, 0.0f};
   GLfloat right_light_position[] = {0.0f, -2.0f, 2.0f, 0.0f};
   GLfloat left_diffuse_light[] =  {1.0f, 1.0f, 1.0f, 1.0f};
   GLfloat right_diffuse_light[] = {1.0f, 1.0f, 1.0f, 1.0f};
   GLfloat color_front[] = {0.0f, 0.5f, 1.0f, 1.0f};
   GLfloat colr_back[] = {1.0f, 0.0f, 0.0f, 1.0f};
   
   glLightfv(GL_LIGHT0, GL_POSITION, left_light_position);
   glLightfv(GL_LIGHT1, GL_POSITION, right_light_position);
   glLightfv(GL_LIGHT0, GL_DIFFUSE, left_diffuse_light);
   glLightfv(GL_LIGHT1, GL_DIFFUSE, right_diffuse_light);
   glMaterialfv(GL_FRONT, GL_DIFFUSE, color_front);
   glMaterialfv(GL_BACK, GL_DIFFUSE, colr_back);
   
   glClearColor(1,1,1,1);
   glColor4f(1,1,0,1);
   meshrendermode_mask = SMOOTH;
   
   std::time(&start);
   frame = 0;
   
   genWorldLimits();
   
   texFloor = new Texture("icons/floor4.png", GL_TEXTURE_2D);
   //~ setGLview();
}

/// A simple opengl drawing callback
void OpenGLFrame::paintGL() {
   
   glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
   glMatrixMode(GL_MODELVIEW);
   glLoadIdentity();
   gluLookAt(cameye[0],cameye[1],cameye[2],camcenter[0],camcenter[1],camcenter[2],0,1,0);
   
   // Draw the 3D cursor
   const Number &scalefactor = (maxcoo[0]-mincoo[0])*(1.5/100);
   drawCursor3D(cursor3D, scalefactor);
   
   glMultMatrixf(&sceneT);
   
   // Draw the floor
   if ((viewitems_mask & FLOOR) == FLOOR)
      drawFloor();
   
   // render the shadows
   if ((viewitems_mask & SHADOW) == SHADOW) {
      glDisable(GL_LIGHTING);
      glPushMatrix();
      glMultMatrixf(shadowMatrix);
      glColor4f(0.0f, 0.08f, 0.0f, 1.0); // shadow color
      
      for (unsigned i=0; i<models.size(); ++i) {
         glPushMatrix();
         glMultMatrixf(&(*tmatrices[i]));
         
         // Render the mesh
         glEnableClientState(GL_VERTEX_ARRAY);
         glEnableClientState(GL_NORMAL_ARRAY);
         typedef Mesh::Vertex Vertex;
         Vertex_iterator vi = models[i]->vertices_begin();
         glVertexPointer(3, GL_FLOAT, sizeof(Vertex), &(vi->point()[0]));
         glNormalPointer(GL_FLOAT, sizeof(Vertex), &(vi->normal()[0]));
         glDrawModel(models[i], FLAT);
         glDisableClientState(GL_VERTEX_ARRAY);
         glDisableClientState(GL_NORMAL_ARRAY);
         
         glPopMatrix();
      }
      glPopMatrix();
      glEnable(GL_LIGHTING);
   }
   
   // Draw the models
   if ((viewitems_mask & MODELDEF) == MODELDEF) {
      for (unsigned i=0; i<models.size(); ++i) {
         glPushMatrix();
         glMultMatrixf(&(*tmatrices[i]));
         
         GLfloat c[4] = {0.0,0.5,1.0,1.0};
         if (i==0)        { c[0]=0.5; c[1]=0.0; c[2]=0.5; c[3]=0.0; }
         else if (i==1)   { c[0]=1.0; c[1]=0.5; c[2]=0.5; c[3]=0.0; }
         glMaterialfv(GL_FRONT, GL_DIFFUSE, c);
         
         // Render the mesh
         glEnableClientState(GL_VERTEX_ARRAY);
         glEnableClientState(GL_NORMAL_ARRAY);
         typedef Mesh::Vertex Vertex;
         Vertex_iterator vi = models[i]->vertices_begin();
         glVertexPointer(3, GL_FLOAT, sizeof(Vertex), &(vi->point()[0]));
         glNormalPointer(GL_FLOAT, sizeof(Vertex), &(vi->normal()[0]));
         glDrawModel(models[i], meshrendermode_mask);
         glDisableClientState(GL_VERTEX_ARRAY);
         glDisableClientState(GL_NORMAL_ARRAY);
         
         glPopMatrix();
      }
   }
   
   // Draw the skeleton
   if ((viewitems_mask & SKELETONDEF) == SKELETONDEF) {
      for (unsigned i=0; i<models.size(); ++i) {
         glPushMatrix();
         glMultMatrixf(&(*tmatrices[i]));
         glDisable(GL_DEPTH_TEST);
         glDrawSkel(models[i]->skeleton);
         glEnable(GL_DEPTH_TEST);
         glPopMatrix();
      }
   }
   
   // FPS info
   if ((viewitems_mask & INFO) == INFO)
      renderInfo();
}

void OpenGLFrame::renderInfo() {
   
   // Render info
   if ((viewitems_mask & INFO) == INFO and not models.empty()) {
      glDisable(GL_LIGHTING);
      glDisable(GL_DEPTH_TEST);
      
      frame++;
      std::time(&end);
      double ddifftime = std::difftime(end, start);
      if (ddifftime > 1) {
         cfps = frame/ddifftime;
         start = end;
         frame = 0;
      }
      
      QString strInfoNv=QString("vertices: %1").arg(nvertices);
      QString strInfoNf=QString("faces: %1").arg(nfaces);
      QString strInfoFPS=QString("FPS: %1").arg(cfps,7,'f',1);
      
      glColor4f(0.0, 0.0, 0.0, 1.0);
      renderText(30,15, strInfoNv);
      renderText(30,30, strInfoNf);
      renderText(30,75, strInfoFPS);
      
      glEnable(GL_LIGHTING);
      glEnable(GL_DEPTH_TEST);
   }
}

void OpenGLFrame::drawFloor() {
   
   glEnable(GL_TEXTURE_2D);
   texFloor->bind();
   
   glDisable(GL_LIGHTING);
   glPolygonMode(GL_FRONT, GL_FILL);
   glPolygonMode(GL_BACK, GL_LINE);
   glColor3f(1.0,1.0,1.0);
   glBegin(GL_QUADS);
   glNormal3f(0.0,1.0,0.0);
   glTexCoord2d(0.0,0.0); glVertex3f(floor[0][0],floor[0][1], floor[0][2]);
   glTexCoord2d(1.0,0.0); glVertex3f(floor[1][0],floor[1][1], floor[1][2]);
   glTexCoord2d(1.0,1.0); glVertex3f(floor[2][0],floor[2][1], floor[2][2]);
   glTexCoord2d(0.0,1.0); glVertex3f(floor[3][0],floor[3][1], floor[3][2]);
   glEnd();
   glEnable(GL_LIGHTING);
   glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
   
   glDisable(GL_TEXTURE_2D);
}

void OpenGLFrame::createShadowProjectionMatrix(float *l, float *e, float *n) {
   
   // These are c and d (corresponding to the tutorial)
   float d = n[0]*l[0] + n[1]*l[1] + n[2]*l[2];
   float c = e[0]*n[0] + e[1]*n[1] + e[2]*n[2] - d;
   
   // Create the matrix. OpenGL uses column by column ordering
   shadowMatrix[0]  = l[0]*n[0]+c;
   shadowMatrix[4]  = n[1]*l[0];
   shadowMatrix[8]  = n[2]*l[0];
   shadowMatrix[12] = -l[0]*c-l[0]*d;
  
   shadowMatrix[1]  = n[0]*l[1];
   shadowMatrix[5]  = l[1]*n[1]+c;
   shadowMatrix[9]  = n[2]*l[1];
   shadowMatrix[13] = -l[1]*c-l[1]*d;
  
   shadowMatrix[2]  = n[0]*l[2];
   shadowMatrix[6]  = n[1]*l[2];
   shadowMatrix[10] = l[2]*n[2]+c;
   shadowMatrix[14] = -l[2]*c-l[2]*d;
  
   shadowMatrix[3]  = n[0];
   shadowMatrix[7]  = n[1];
   shadowMatrix[11] = n[2];
   shadowMatrix[15] = -d;
}

void OpenGLFrame::genWorldLimits() {
   
   if (models.empty()) return;
   
   if (models.size() == 1) {
      MeshWithSkeleton *currentmodel = models.back();
      mincoo[0] = currentmodel->mincoo[0]; mincoo[1] = currentmodel->mincoo[1]; mincoo[2] = currentmodel->mincoo[2];
      maxcoo[0] = currentmodel->maxcoo[0]; maxcoo[1] = currentmodel->maxcoo[1]; maxcoo[2] = currentmodel->maxcoo[2];
   }
   else {
      MeshWithSkeleton *currentmodel = models.back();
      Number minx = currentmodel->mincoo[0], miny = currentmodel->mincoo[1], minz = currentmodel->mincoo[2];
      Number maxx = currentmodel->maxcoo[0], maxy = currentmodel->maxcoo[1], maxz = currentmodel->maxcoo[2];
      
      (minx<mincoo[0])? (mincoo[0]=minx):0; 
      (miny<mincoo[1])? (mincoo[1]=miny):0; 
      (minz<mincoo[2])? (mincoo[2]=minz):0; 
      
      (maxx>maxcoo[0])? (maxcoo[0]=maxx):0; 
      (maxy>maxcoo[1])? (maxcoo[1]=maxy):0; 
      (maxz>maxcoo[2])? (maxcoo[2]=maxz):0; 
   }
   
   float xc = mincoo[0] + 0.5*(maxcoo[0]-mincoo[0]);
   float yc = mincoo[1] + 0.5*(maxcoo[1]-mincoo[1]);
   
   float WorldWidth  = abs(maxcoo[0]-mincoo[0]);
   float WorldHeight = abs(maxcoo[1]-mincoo[1]);
   
   if ((WorldHeight/WorldWidth) > ((float)height()/(float)width())) {
      WorldWidth = WorldHeight / ((float)height()/(float)width());
   }
   else if ((WorldHeight/WorldWidth) < ((float)height()/(float)width())) {
      WorldHeight = WorldWidth * ((float)height()/(float)width());
   }
   
   // world limits
   mincoo[0] = xc - 0.5*WorldWidth;
   mincoo[1] = yc - 0.5*WorldHeight;
   
   maxcoo[0] = xc + 0.5*WorldWidth;
   maxcoo[1] = yc + 0.5*WorldHeight;
   
   // center camera
   camcenter[0] = xc;
   camcenter[1] = yc;
   camcenter[2] = mincoo[2] + 0.5*(maxcoo[2]-mincoo[2]);
}

/// It sets the projection/modelview matrices
void OpenGLFrame::setGLview() {
   
   glMatrixMode(GL_PROJECTION);
   glLoadIdentity();
   
   WorldWidth  = abs(maxcoo[0]-mincoo[0])*0.5;
   WorldHeight = abs(maxcoo[1]-mincoo[1])*0.5;
   
   objDistance = 0.8660*(maxcoo[1]-mincoo[1]); /// sqrt(3)/2 = 0.8660
   //~ objDistance = WorldHeight;
   nearplane = objDistance - objDistance*0.5;
   farplane  = nearplane + 20.0;
   
   cameye[0] = camcenter[0];
   cameye[1] = camcenter[1];
   cameye[2] = maxcoo[2] + objDistance;
   
   if (isProjOrtho) 
      glOrtho(-WorldWidth*zoomFactor,  WorldWidth*zoomFactor, 
              -WorldHeight*zoomFactor, WorldHeight*zoomFactor, 
               nearplane*0.5, farplane);
   else 
      gluPerspective(fovy*zoomFactor, (GLfloat)width()/(GLfloat)height(), nearplane, farplane);
   
   glMatrixMode(GL_MODELVIEW);
   glLoadIdentity();
   glViewport(0, 0, width(), height());
}
   
/// A simple resize callback.
/// @param width the width of the new window.
/// @param height the height of the new window.
void OpenGLFrame::resizeGL(int width, int height) {
   
   setGLview();
   arcball.setBounds(width, height);  //Update mouse bounds for the arcball
}

/// Callback for handling mouse button press.
/// @param event encapsulates the event's info.
void OpenGLFrame::mousePressEvent(QMouseEvent *event) {
   
   xini=event->x(); yini=height()-event->y();
   if (event->button() == Qt::MidButton) {
      arcball.click(xini,yini);
   }
   else if (event->button() == Qt::RightButton) {
      grabLast = grabStart = screenToWorld(xini, yini);
   }
   sceneIniT = sceneT;
   glDraw();
}

/// Callback for handling mouse movements.
/// @param event encapsulates the event's info.
void OpenGLFrame::mouseMoveEvent(QMouseEvent *event) {
   
   if ((event->buttons() & Qt::MidButton)) { // rotations handler
      AMatrix<float> mT;
      arcball.drag(event->x(), height()-event->y(), &mT);
      sceneT = mT*sceneIniT;
   }
   else if (event->buttons() & Qt::RightButton) { // translations handler
      Vector3 t = screenToWorld(xini, yini, event->x(), height()-event->y());
      AMatrix<float> mT;
      mT.identity();
      mT.translation(t[0], t[1], t[2]);
      sceneT = sceneIniT*mT;
   }
   glDraw();
}

/// Callback for handling mouse button release.
/// @param event encapsulates the event's info.
void OpenGLFrame::mouseReleaseEvent(QMouseEvent *event) {
   
   switch (interactionMode) {
      case SELECT_MODE: {
         break;
      }
      case VIEW_MODE: {
         break;
      }
   }
   event->accept(); 
}

/// Inplements zoom operations using the mouse wheel
void OpenGLFrame::wheelEvent(QWheelEvent *e) {
   
   //~ if (e->delta()>0) zoomFactor+= 0.1;
   //~ else              zoomFactor-= 0.1;
   //~ e->accept(); 
   //~ setGLview();
   //~ glDraw();
   
   if (e->delta()>0) zoomIn();
   else              zoomOut();
      
   e->accept(); 
}

void OpenGLFrame::keyPressEvent(QKeyEvent *event) {
   
   if (event->key() == Qt::Key_Escape) {
      exit(0);
   }
}

/// Implements the "zoomin" operation
void OpenGLFrame::zoomIn() {
   
   AMatrix<float> mT;
   mT.identity();
   mT.scaling(1.2);
   sceneT = mT*sceneT;
   
   glDraw();
}

/// Implements the "zoomout" operation
void OpenGLFrame::zoomOut() {
   
   AMatrix<float> mT;
   mT.identity();
   mT.scaling(1.0/1.2);
   sceneT = mT*sceneT;
   
   glDraw();
}

/// Implements the "zoomall" operation
void OpenGLFrame::zoomAll() {
   
   sceneT.identity();
   glDraw();
}

/// Returns the world coordinates of a point in screen space
Point3 OpenGLFrame::screenToWorld(int x, int y) {
   
   glGetIntegerv(GL_VIEWPORT, viewport);
   glGetDoublev(GL_PROJECTION_MATRIX, pMtx);
   glGetDoublev(GL_MODELVIEW_MATRIX, mMtx);
   
   GLdouble xw, yw, zw;
   gluUnProject(x, y, 1.0, mMtx, pMtx, viewport, &xw, &yw, &zw);
   return Point3(xw, yw, zw);
}

/// Returns the translation vector in world coordinates of two points in screen space
Vector3 OpenGLFrame::screenToWorld(int xi, int yi, int xe, int ye) {
   
   glGetIntegerv(GL_VIEWPORT, viewport);
   //~ glGetDoublev(GL_PROJECTION_MATRIX, pMtx);
   glGetDoublev(GL_MODELVIEW_MATRIX, mMtx);
   
   /// Compute the world coordinates using the orthographic projection
   glMatrixMode(GL_PROJECTION);
   glPushMatrix();
   glLoadIdentity();
   glOrtho(-WorldWidth*zoomFactor,  WorldWidth*zoomFactor, 
           -WorldHeight*zoomFactor, WorldHeight*zoomFactor, 
            nearplane, farplane);
   glGetDoublev(GL_PROJECTION_MATRIX, pMtx);
   glPopMatrix();
   
   GLdouble ws[3], we[3];
   gluUnProject(xi, yi, 0, mMtx, pMtx, viewport, &ws[0], &ws[1], &ws[2]);
   gluUnProject(xe, ye, 0, mMtx, pMtx, viewport, &we[0], &we[1], &we[2]);
   
   return Vector3(we[0]-ws[0], we[1]-ws[1], we[2]-ws[2]);
}

void OpenGLFrame::animateFrame(int animIndex) {
   
   for (unsigned i=0; i<animators.size(); ++i) {
      animators[i]->frame(animIndex);
   }
   glDraw();
}

void OpenGLFrame::record() {
   
   if (is_pic_capturing) {
      QPixmap qp = renderPixmap(0,0,false);
      QString fileName;
      if (id_picgrab<10)        fileName = QString("./output/pic0000%1.png").arg(id_picgrab);
      else if (id_picgrab<100)  fileName = QString("./output/pic000%1.png").arg(id_picgrab);
      else if (id_picgrab<1000) fileName = QString("./output/pic00%1.png").arg(id_picgrab);
      else                      fileName = QString("./output/pic0%1.png").arg(id_picgrab);
         
      bool ok = qp.save(fileName,"PNG");
   }
   if (is_mesh_capturing) {
      MeshWithSkeleton *currentmodel = models.back();
      QString fileName = QString("./output/mesh%1.off").arg(id_picgrab);
      currentmodel->saveShapeOFF(fileName.toStdString().c_str());
   }
   ++id_picgrab;
}
